import type { InputNumberProps } from './index';
import floor from 'lodash/floor';

/** 判断是否正常数字 */
export const isValidNumber = (value: any) => {
  return typeof value === 'number' && !Number.isNaN(value) && Number.isFinite(value);
};

/** 默认formatter */
export const inputNumberFormatter: InputNumberProps['formatter'] = (value, options) => {
  let val: any = '';
  if (typeof value === 'string' && value) {
    val = Number(value);
  } else if (typeof value === 'number') {
    val = value;
  }
  if (!isValidNumber(val)) {
    val = '';
  }
  val = String(val);
  return val;
};

/** 默认parser */
export const inputNumberParser: InputNumberProps['parser'] = (value, options) => {
  if (!value) return undefined;
  let num = Number(value);
  if (!isValidNumber(num)) return undefined;
  if (typeof options?.precision === 'number') {
    // 保留precision位小数点
    num = floor(num, options.precision);
  }
  return num;
};

/** inputNumber-props 千分位 */
export const inputNumberPercentilesProps: Pick<InputNumberProps, 'formatter' | 'parser'> = {
  formatter: value => {
    let val = '';
    if (typeof value === 'number') {
      if (isValidNumber(value)) {
        val = String(value);
      }
    } else if (typeof value === 'string') {
      let tempVal = Number(value);
      if (isValidNumber(tempVal)) {
        val = String(tempVal);
      }
    }
    val = val.toString().replace(/\d+/, function (n) {
      return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
        return $1 + ',';
      });
    });
    return val;
  },
  parser: (value, options) => {
    if (!value) return undefined;
    // 把千分位字符串转成数字，类型为number
    let num = Number(value.replace(/,/g, ''));
    if (!isValidNumber(num)) return undefined;
    return inputNumberParser(String(num), options);
  },
};

/** inputNumber-props 百分比录入, 录入0.1, 显示10%  */
export const inputNumberPercentProps: Pick<InputNumberProps, 'formatter' | 'parser'> = {
  formatter: value => {
    let val = '';
    if (typeof value === 'string') {
      const temVal = Number(value);
      if (isValidNumber(temVal)) {
        val = String(temVal * 100);
      }
    } else if (typeof value === 'number') {
      if (isValidNumber(value)) {
        val = String(value * 100);
      }
    }
    if (val) return val + '%';
    return '';
  },
  parser: (value, options) => {
    if (!value) return undefined;
    let num = Number(value.replace('%', ''));
    if (!isValidNumber(num)) return undefined;
    return inputNumberParser(String(num / 100), options);
  },
};
